package cc.vv.baselibrary.view;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import cc.vv.baselibrary.R;


/**
 * md风格的dialog工具类
 *
 * @author dup dupeng@vv.cc
 * @date 2018/3/23
 */
public class LKDialog {

    /**
     * context
     */
    private Context mContext;
    /**
     * 是否可被取消
     */
    private boolean mCancel;
    /**
     * dialog
     */
    private AlertDialog mAlertDialog;
    /**
     * builder
     */
    private LKDialog.Builder mBuilder;
    /**
     * dialog的布局
     */
    private View mView;
    /**
     * title文本资源id
     */
    private int mTitleResId;
    /**
     * title文本
     */
    private CharSequence mTitle;
    /**
     * 内容文本id
     */
    private int mMessageResId;
    /**
     * 内容文本
     */
    private CharSequence mMessage;
    /**
     * 右边按钮
     */
    private TextView mPositiveButton;
    /**
     * 左边按钮
     */
    private TextView mNegativeButton;
    /**
     * 是否正在显示
     */
    private boolean mHasShow = false;
    /**
     * dialog背景
     */
    private int mBackgroundResId = -1;
    /**
     * dialog背景
     */
    private Drawable mBackgroundDrawable;
    /**
     * 自定义的内容控件
     */
    private View mMessageContentView;
    /**
     * 自定义的内容控件
     */
    private int mMessageContentViewResId;
    /**
     * 消失监听
     */
    private DialogInterface.OnDismissListener mOnDismissListener;
    /**
     * 左右按钮文字资源
     */
    private int rightTextId = -1, leftTextId = -1;
    /**
     * 左右按钮文字资源
     */
    private String rightText, leftText;
    /**
     * 左右按钮监听
     */
    private View.OnClickListener rightListener, leftListener;


    public LKDialog(Context context) {
        this.mContext = context;
    }

    /**
     * 显示dialog
     */
    public void show() {
        if (!mHasShow) {
            mBuilder = new Builder();
        } else {
            mAlertDialog.show();
        }
        mHasShow = true;
    }

    /**
     * dialog消失
     */
    public void dismiss() {
        mAlertDialog.dismiss();
    }

    /**
     * 替换dialog布局
     *
     * @param view
     * @return
     */
    public LKDialog setView(View view) {
        mView = view;
        if (mBuilder != null) {
            mBuilder.setView(view);
        }
        return this;
    }

    /**
     * 设置dialog中间的布局.不是设置整个dialog布局.(默认的message控件会被此替换掉)
     *
     * @param view
     * @return
     */
    public LKDialog setContentView(View view) {
        mMessageContentView = view;
        mMessageContentViewResId = 0;
        if (mBuilder != null) {
            mBuilder.setContentView(mMessageContentView);
        }
        return this;
    }


    /**
     * 设置dialog中间的布局.不是设置整个dialog布局.(默认的message控件会被此替换掉)
     *
     * @param layoutResId resource ID to be inflated
     */
    public LKDialog setContentView(int layoutResId) {
        mMessageContentViewResId = layoutResId;
        mMessageContentView = null;
        if (mBuilder != null) {
            mBuilder.setContentView(layoutResId);
        }
        return this;
    }

    /**
     * 设置dialog背景
     *
     * @param drawable
     * @return
     */
    public LKDialog setBackground(Drawable drawable) {
        mBackgroundDrawable = drawable;
        if (mBuilder != null) {
            mBuilder.setBackground(mBackgroundDrawable);
        }
        return this;
    }


    /**
     * 设置dialog背景
     *
     * @param resId
     * @return
     */
    public LKDialog setBackgroundResource(int resId) {
        mBackgroundResId = resId;
        if (mBuilder != null) {
            mBuilder.setBackgroundResource(mBackgroundResId);
        }
        return this;
    }


    /**
     * 设置标题
     *
     * @param resId
     * @return
     */
    public LKDialog setTitle(int resId) {
        mTitleResId = resId;
        if (mBuilder != null) {
            mBuilder.setTitle(resId);
        }
        return this;
    }

    /**
     * 设置标题
     *
     * @param title
     * @return
     */
    public LKDialog setTitle(String title) {
        mTitle = title;
        if (mBuilder != null) {
            mBuilder.setTitle(title);
        }
        return this;
    }


    /**
     * 设置内容
     *
     * @param resId
     * @return
     */
    public LKDialog setMessage(int resId) {
        mMessageResId = resId;
        if (mBuilder != null) {
            mBuilder.setMessage(resId);
        }
        return this;
    }

    /**
     * 设置内容
     *
     * @param message
     * @return
     */
    public LKDialog setMessage(String message) {
        mMessage = message;
        if (mBuilder != null) {
            mBuilder.setMessage(message);
        }
        return this;
    }

    public TextView getRightButton() {
        return mPositiveButton;
    }


    public TextView getLeftButton() {
        return mNegativeButton;
    }


    /**
     * 设置右按钮.不调用此方法,就不会显示
     *
     * @param resId    按钮文字   -1:button不显示
     * @param listener
     * @return
     */
    public LKDialog setRightButton(int resId, final View.OnClickListener listener) {
        this.rightTextId = resId;
        this.rightListener = listener;
        return this;
    }


    /**
     * 设置右按钮.不调用此方法,就不会显示
     *
     * @param text     按钮文字    为空:button不显示
     * @param listener
     * @return
     */
    public LKDialog setRightButton(String text, final View.OnClickListener listener) {
        this.rightText = text;
        this.rightListener = listener;
        return this;
    }

    /**
     * 设置左按钮.不调用此方法,就不会显示
     *
     * @param resId    按钮文字   -1:button不显示
     * @param listener
     * @return
     */
    public LKDialog setLeftButton(int resId, final View.OnClickListener listener) {
        this.leftTextId = resId;
        this.leftListener = listener;
        return this;
    }

    /**
     * 设置左按钮.不调用此方法,就不会显示
     *
     * @param text     按钮文字    为空:button不显示
     * @param listener
     * @return
     */
    public LKDialog setLeftButton(String text, final View.OnClickListener listener) {
        this.leftText = text;
        this.leftListener = listener;
        return this;
    }


    /**
     * 设置点击外部,或返回键是否有用
     *
     * @param cancel 是否可点击外部,或返回键 取消dialog
     */
    public LKDialog setCanceledOnTouchOutside(boolean cancel) {
        this.mCancel = cancel;
        if (mBuilder != null) {
            mBuilder.setCanceledOnTouchOutside(mCancel);
        }
        return this;
    }

    /**
     * 设置消失监听
     *
     * @param onDismissListener
     * @return
     */
    public LKDialog setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        this.mOnDismissListener = onDismissListener;
        return this;
    }


    private class Builder {

        private TextView mTitleView;
        private ViewGroup mMessageContentRoot;
        private TextView mMessageView;
        private Window mAlertDialogWindow;
        private LinearLayout mButtonLayout;


        private Builder() {
            mAlertDialog = new AlertDialog.Builder(mContext).create();
            mAlertDialog.show();

            mAlertDialog.getWindow()
                    .clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                            WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            mAlertDialog.getWindow()
                    .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE);

            mAlertDialogWindow = mAlertDialog.getWindow();
            mAlertDialogWindow.setBackgroundDrawable(
                    new ColorDrawable(Color.TRANSPARENT));

            View contentView = LayoutInflater.from(mContext)
                    .inflate(R.layout.view_material_dialog, null);
            contentView.setFocusable(true);
            contentView.setFocusableInTouchMode(true);

            mAlertDialogWindow.setContentView(contentView);

            mTitleView = mAlertDialogWindow.findViewById(R.id.tv_vmd_titletv);
            mMessageView = mAlertDialogWindow.findViewById(R.id.tv_vmd_message);
            mButtonLayout = mAlertDialogWindow.findViewById(R.id.ll_vmd_buttonLayout);
            mPositiveButton = mButtonLayout.findViewById(R.id.btn_vmd_btn_p);
            mNegativeButton = mButtonLayout.findViewById(R.id.btn_vmd_btn_n);
            mMessageContentRoot = mAlertDialogWindow.findViewById(
                    R.id.sv_vmd_message_content_root);
            if (mView != null) {
                LinearLayout linearLayout = mAlertDialogWindow.findViewById(
                        R.id.ll_vmd_contentView);
                linearLayout.removeAllViews();
                linearLayout.addView(mView);
            }
            if (mTitleResId != 0) {
                setTitle(mTitleResId);
            }
            if (mTitle != null) {
                setTitle(mTitle);
            }
            if (mTitle == null && mTitleResId == 0) {
                mTitleView.setVisibility(View.GONE);
            }
            if (mMessageResId != 0) {
                setMessage(mMessageResId);
            }
            if (mMessage != null) {
                setMessage(mMessage);
            }
            if (rightTextId != -1) {
                mButtonLayout.setVisibility(View.VISIBLE);
                mPositiveButton.setVisibility(View.VISIBLE);
                mPositiveButton.setText(rightTextId);
                mPositiveButton.setOnClickListener(rightListener);
            }
            if (leftTextId != -1) {
                mButtonLayout.setVisibility(View.VISIBLE);
                mNegativeButton.setVisibility(View.VISIBLE);
                mNegativeButton.setText(leftTextId);
                mNegativeButton.setOnClickListener(leftListener);
            }
            if (!isNullOrEmpty(rightText)) {
                mButtonLayout.setVisibility(View.VISIBLE);
                mPositiveButton.setVisibility(View.VISIBLE);
                mPositiveButton.setText(rightText);
                mPositiveButton.setOnClickListener(rightListener);
            }

            if (!isNullOrEmpty(leftText)) {
                mButtonLayout.setVisibility(View.VISIBLE);
                mNegativeButton.setVisibility(View.VISIBLE);
                mNegativeButton.setText(leftText);
                mNegativeButton.setOnClickListener(leftListener);
            }
            if (isNullOrEmpty(rightText) && rightTextId == -1) {
                mPositiveButton.setVisibility(View.GONE);
            }
            if (isNullOrEmpty(leftText) && leftTextId == -1) {
                mNegativeButton.setVisibility(View.GONE);
            }
            if (mBackgroundResId != -1) {
                LinearLayout linearLayout = mAlertDialogWindow.findViewById(
                        R.id.ll_vmd_background);
                linearLayout.setBackgroundResource(mBackgroundResId);
            }
            if (mBackgroundDrawable != null) {
                LinearLayout linearLayout = mAlertDialogWindow.findViewById(
                        R.id.ll_vmd_background);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    linearLayout.setBackground(mBackgroundDrawable);
                }
            }

            if (mMessageContentView != null) {
                this.setContentView(mMessageContentView);
            } else if (mMessageContentViewResId != 0) {
                this.setContentView(mMessageContentViewResId);
            }
            mAlertDialog.setCanceledOnTouchOutside(mCancel);
            mAlertDialog.setCancelable(mCancel);
            if (mOnDismissListener != null) {
                mAlertDialog.setOnDismissListener(mOnDismissListener);
            }
        }


        public void setTitle(int resId) {
            mTitleView.setText(resId);
        }


        public void setTitle(CharSequence title) {
            mTitleView.setText(title);
        }


        public void setMessage(int resId) {
            if (mMessageView != null) {
                mMessageView.setText(resId);
            }
        }


        public void setMessage(CharSequence message) {
            if (mMessageView != null) {
                mMessageView.setText(message);
            }
        }


        public void setView(View view) {
            LinearLayout l = mAlertDialogWindow.findViewById(R.id.ll_vmd_contentView);
            l.removeAllViews();
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(layoutParams);

            view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    mAlertDialogWindow.setSoftInputMode(
                            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    // show imm
                    InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
                            Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                            InputMethodManager.HIDE_IMPLICIT_ONLY);
                }
            });

            l.addView(view);

            if (view instanceof ViewGroup) {

                ViewGroup viewGroup = (ViewGroup) view;

                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    if (viewGroup.getChildAt(i) instanceof EditText) {
                        EditText editText = (EditText) viewGroup.getChildAt(i);
                        editText.setFocusable(true);
                        editText.requestFocus();
                        editText.setFocusableInTouchMode(true);
                    }
                }
                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    if (viewGroup.getChildAt(i) instanceof AutoCompleteTextView) {
                        AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) viewGroup
                                .getChildAt(i);
                        autoCompleteTextView.setFocusable(true);
                        autoCompleteTextView.requestFocus();
                        autoCompleteTextView.setFocusableInTouchMode(true);
                    }
                }
            }
        }


        public void setContentView(View contentView) {
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            contentView.setLayoutParams(layoutParams);
            if (contentView instanceof ListView) {
                setListViewHeightBasedOnChildren((ListView) contentView);
            }
            LinearLayout linearLayout = mAlertDialogWindow.findViewById(
                    R.id.ll_vmd_message_content_view);
            if (linearLayout != null) {
                linearLayout.removeAllViews();
                linearLayout.addView(contentView);
            }
            for (int i = 0; i < (linearLayout != null ? linearLayout.getChildCount() : 0); i++) {
                if (linearLayout.getChildAt(i) instanceof AutoCompleteTextView) {
                    AutoCompleteTextView autoCompleteTextView
                            = (AutoCompleteTextView) linearLayout.getChildAt(i);
                    autoCompleteTextView.setFocusable(true);
                    autoCompleteTextView.requestFocus();
                    autoCompleteTextView.setFocusableInTouchMode(true);
                }
            }
        }


        /**
         * 设置在scrollview中放置的layout
         *
         * @param layoutResId
         */
        public void setContentView(int layoutResId) {
            mMessageContentRoot.removeAllViews();
            LayoutInflater.from(mMessageContentRoot.getContext())
                    .inflate(layoutResId, mMessageContentRoot);
        }


        public void setBackground(Drawable drawable) {
            LinearLayout linearLayout = (LinearLayout) mAlertDialogWindow.findViewById(
                    R.id.ll_vmd_background);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                linearLayout.setBackground(drawable);
            }
        }


        public void setBackgroundResource(int resId) {
            LinearLayout linearLayout = mAlertDialogWindow.findViewById(
                    R.id.ll_vmd_background);
            linearLayout.setBackgroundResource(resId);
        }


        public void setCanceledOnTouchOutside(boolean canceledOnTouchOutside) {
            mAlertDialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
            mAlertDialog.setCancelable(canceledOnTouchOutside);
        }
    }


    private boolean isNullOrEmpty(String nText) {
        return nText == null || nText.isEmpty();
    }


    private void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    private static boolean isLollipop() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }
}